import { t } from 'i18next'
import createVanilla from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { Cascade, InitOption, MccCurrentMt, MccModel, Meeting } from './interface'
import { flatGetAllMeetingList, getCurrentMeetingMts, isCascadeTree, mtsTranslator, SelectMtEntity } from './translator'
import { fetchAllMccMts } from '@/api/manager/main'

export type MccOption = {
	isCascade: boolean
	mccCurrentMts: MccCurrentMt[]
	cascadeList: Cascade[]
	currentCascadeId: string
}
export type IStore = InitOption &
	MccOption & {
		update: (d: Partial<Omit<InitOption & MccOption, 'mccModel'>>) => void
		reset: () => void
		initMcc: (mccModel: MccModel<Meeting>) => void
		onRemoveRoom: () => void
		onSubmit: (s: {
			selectedList: Required<Omit<SelectMtEntity, 'meetingType'>>[]
			cascadeType?: { [key: string]: 0 | 1 }
			smcuMtid: string
		}) => void
	}

const initialState: InitOption & MccOption = {
	title: t('添加与会方'), //邀请终端弹窗头文字
	isOpen: false, //弹窗打开状态
	curTemplateE164: '', //当前预分配会议号或者是会控当前会议的e164号, 为了知道级联情况
	meetingType: 1, //会议类型 0:传统，1:端口,2:sfu
	maxRate: 2048, //最大码率
	showTrees: ['org', 'monitor', 'template'], //显示的tab tree
	isSuperMeeting: false, //是否是超大方
	isSupportRtc: true, //是否支持rtc
	isOnlyMakeUser: false, //是否只是选人员，不调整码率等
	smartCascadeMode: 0, //智能级联
	//会控专属
	isMcc: false, //是否会控
	meetingMoid: undefined, // 会控才有的meetingMoid
	mccModel: undefined, //todo 会控才有的MccModel级联人员信息, 【实时变动暂未做】
	isCascade: false, //是否级联
	mccCurrentMts: [], //当前所选的级联会议的终端列表
	cascadeList: [], //会控级联的下拉会议列表
	currentCascadeId: '0.0.0.0_0', //当前所选的级联会议
}
export const store = createVanilla<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		//通用提交
		onSubmit: () => {},
		//创会专属
		onRemoveRoom: () => {}, //移除选择的会议室的监听回调
		//会控专属
		//会控才初始化调用
		initMcc: async (mccModel) => {
			let isCascade = isCascadeTree(mccModel)
			let mccCurrentMts = mtsTranslator(getCurrentMeetingMts(mccModel))
			let cascadeList = flatGetAllMeetingList(mccModel)
			let currentCascadeId = get().currentCascadeId
			let smartCascadeMode = get().smartCascadeMode
			let meetingMoid = get().meetingMoid
			if (smartCascadeMode === 1) {
				cascadeList = [
					{
						name: t('智能接入'),
						confLevel: 2,
						id: 'zn',
					},
					...cascadeList,
				]
				currentCascadeId = 'zn'
				const list = await fetchAllMccMts(meetingMoid || '')
				if (list) {
					let _mts: MccCurrentMt[] = list.map((item) => {
						return {
							account: item.account,
							accountType: item.account_type,
							e164: item.e164,
							moid: item.moid,
						}
					})
					mccCurrentMts = _mts
				}
			}
			set({ isMcc: true, mccModel, isCascade, mccCurrentMts, cascadeList, currentCascadeId })
		},
	}))
)
export const useMtAddStore = create(store)
